import { request } from '../request';

// 定时任务相关类型定义
export interface ScheduleTask {
  taskId: string;
  taskName: string;
  description: string;
  creator: string;
  createTime: string;
  running: boolean;
  runnable: boolean;
  cron: string;
  beanName: string;
  methodName: string;
  nodeIp?: string;
  nodePort?: string;
}

export interface ScheduleTaskConfig {
  taskName: string;
  description: string;
  cron: string;
  beanName: string;
  methodName: string;
  nodeIp?: string;
  nodePort?: string;
  enabled?: boolean; // 添加任务状态字段
}

export interface ScheduleTaskInfo {
  config: ScheduleTaskConfig;
  running: boolean;
  runnable: boolean;
}

export interface ScheduleTaskResponse {
  [taskId: string]: ScheduleTaskInfo;
}

export interface AvailableClassesResponse {
  [className: string]: string[];
}

// 定时任务执行记录相关类型定义
export interface ScheduleTaskExecutionRecord {
  executionId: string;
  taskId: string;
  taskName: string | null;
  startTime: string;
  endTime: string | null;
  duration: number;
  status: 'SUCCESS' | 'FAILED' | 'RUNNING';
  result: string | null;
  errorMessage: string | null;
  logs: string | null;
}

export interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}

/** 获取所有可用的定时任务类及其方法名 */
export function fetchScheduleTaskClasses() {
  return request<AvailableClassesResponse>({
    url: '/scheduled-task/available',
    method: 'get'
  });
}

/** 获取定时任务列表 */
export function fetchScheduleTask() {
  return request<ScheduleTaskResponse>({
    url: '/scheduled-task/list',
    method: 'get'
  });
}

/** 创建定时任务 */
export function createScheduleTask(data: ScheduleTaskConfig) {
  return request({
    url: '/scheduled-task/create',
    method: 'post',
    data
  });
}

/** 更新定时任务 */
export function updateScheduleTask(taskId: string, data: ScheduleTaskConfig) {
  return request({
    url: `/scheduled-task/update/${taskId}`,
    method: 'post',
    data
  });
}

/** 启动定时任务 */
export function startScheduleTask(taskId: string) {
  return request({
    url: `/scheduled-task/start/${taskId}`,
    method: 'post'
  });
}

/** 停止定时任务 */
export function stopScheduleTask(taskId: string) {
  return request({
    url: `/scheduled-task/stop/${taskId}`,
    method: 'post'
  });
}

/** 删除定时任务 */
export function deleteScheduleTask(taskId: string) {
  return request({
    url: `/scheduled-task/delete/${taskId}`,
    method: 'post'
  });
}

/** 立即执行定时任务 */
export function executeScheduleTask(taskId: string) {
  return request({
    url: `/scheduled-task/execute/${taskId}`,
    method: 'post'
  });
}

/** 获取定时任务执行记录 */
export function fetchScheduleTaskExecutionRecords(taskId: string) {
  return request<ApiResponse<ScheduleTaskExecutionRecord[]>>({
    url: `/scheduled-task/executions/${taskId}`,
    method: 'get'
  });
}
